package com.halden.mycache.support.aop;

import com.halden.mycache.support.listener.ISlowLogListener;
import com.halden.mycache.support.saveStrategy.AOFSaveStrategy.IAOFSaveStrategy;
import com.halden.mycache.support.saveStrategy.AOFSaveStrategy.SaveContext;
import org.apache.commons.codec.binary.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Author: halden
 * @Data:2023/2/15 16:07
 * @Description:
 */
@Component
@Aspect
public class AOFAspect {

    /**
     * 存储的全路径文件名
     */
    private static String fileName;

    /**
     * aof持久化保存
     */
    private static IAOFSaveStrategy aofSaveStrategy;

    /**
     * 设置全路径文件名
     * @param file
     */
    public static void setFileName(String file){
        fileName = file;
    }

    /**
     * 设置aof策略
     * @param saveStrategy
     */
    public static void setAofSaveStrategy(IAOFSaveStrategy saveStrategy){
        aofSaveStrategy = saveStrategy;
        if (fileName != null && fileName.length() > 0){
            aofSaveStrategy.startStrategy(fileName);
        }
    }

    /**
     * 确定切点
     */
    @Pointcut("@annotation(com.halden.mycache.support.aop.CacheInterceptor)")
    public void action() {
    }

    @AfterReturning("action()")
    public void after(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        //获取注解，判断其中参数
        CacheInterceptor cacheInterceptor = method.getAnnotation(CacheInterceptor.class);
        if (!cacheInterceptor.aof()){
            return;
        }
        SaveContext saveContext = new SaveContext();
        saveContext.setMethod(method);
        saveContext.setParams(joinPoint.getArgs());
        aofSaveStrategy.save(saveContext);
    }
}
